package com.hbnu.client;
import com.hbnu.client.handler.ExceptionHandler;
import com.hbnu.client.handler.ResponseHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;


public class FileClient {
    private final Bootstrap bootstrap;
    private final EventLoopGroup group;


    public FileClient(){
        this.bootstrap = new Bootstrap(); // 用于客户端引导
        this.group = new NioEventLoopGroup();  // 使用 NIO 事件循环
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                //.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)// 5 秒超时
               // .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        //日志
                        ch.pipeline().addLast(loggingHandler);
                        ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                        ch.pipeline().addLast(new ObjectEncoder());
                        //响应接收handle
                        ch.pipeline().addLast(new ResponseHandler());
                        ch.pipeline().addLast(new ExceptionHandler());

                    }
                }); // 客户端初始化
    }

    public Bootstrap getBootstrap() {
        return bootstrap;
    }

    public void stop() {
        try {
            group.shutdownGracefully().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
